package com.xuerhua.yxt.controller.sys.signup;

import com.xuerhua.yxt.common.AdminUser;
import com.xuerhua.yxt.common.RspResult;
import com.xuerhua.yxt.common.enums.Status;
import com.xuerhua.yxt.common.enums.StudentSignUpType;
import com.xuerhua.yxt.common.enums.StudentSignupStaus;
import com.xuerhua.yxt.controller.BaseController;
import com.xuerhua.yxt.excel.CellUtil;
import com.xuerhua.yxt.model.Grid;
import com.xuerhua.yxt.model.StudentSignUp;
import com.xuerhua.yxt.page.Page;
import com.xuerhua.yxt.reqVo.SignupResultVO;
import com.xuerhua.yxt.service.IStudentSignUpService;
import com.xuerhua.yxt.utils.ExcelExportUtil;
import com.xuerhua.yxt.utils.ExportSetInfoUtil;
import com.xuerhua.yxt.utils.StringUtil;
import com.xuerhua.yxt.vo.SignUpQueryVO;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

@RequestMapping("sys/signUp/newStudent")
@Controller
public class SysNewStudentController extends BaseController {

    @Autowired
    private IStudentSignUpService studentSignUpService;

    @RequestMapping(value = {"", "/"})
    public String Index() {
        return "sys/signup/newStudent";
    }

    @RequestMapping("print/{ids}")
    public String printById(@PathVariable String ids, Model model) {
        List list = this.studentSignUpService.selectListByIds(StudentSignUpType.NEW_STUDENT.getCode(), ids);
        model.addAttribute("list", list);
        model.addAttribute("signupType", StudentSignUpType.NEW_STUDENT.getDesc());
        return "sys/signup/studentList";
    }

    @RequestMapping("printList")
    public String printList(SignUpQueryVO vo, Model model) {
        vo.setSignUpType(StudentSignUpType.NEW_STUDENT.getCode());
        Page page = new Page();
        page.setParams(vo);
        page.setPageNo(vo.getPage());
        page.setPageSize(Integer.MAX_VALUE - 1);
        List list = this.studentSignUpService.selectListByPage(page);
        model.addAttribute("list", list);
        model.addAttribute("signupType", StudentSignUpType.NEW_STUDENT.getDesc());
        return "sys/signup/studentList";
    }

    @RequestMapping("pageQuery")
    @ResponseBody
    Object pageQuery(SignUpQueryVO vo) {
        try {
            vo.setSignUpType(StudentSignUpType.NEW_STUDENT.getCode());
            Page page = new Page();
            page.setParams(vo);
            page.setPageNo(vo.getPage());
            page.setPageSize(vo.getRows());
            List list = this.studentSignUpService.selectListByPage(page);
            Grid grid = new Grid();
            grid.setRows(list);
            grid.setTotal(page.getTotalRecord());
            return grid;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @RequestMapping("ok")
    @ResponseBody
    Object Ok(SignupResultVO record) {
        try {
            record.setStatus("000");
            record.setSignupType(StudentSignUpType.NEW_STUDENT.getCode());
            this.studentSignUpService.updateSignupResult(record);
            return new RspResult(Status.SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new RspResult(Status.FAIL);
    }

    @RequestMapping("no")
    @ResponseBody
    Object no(SignupResultVO record) {
        try {
            record.setStatus("002");
            record.setSignupType(StudentSignUpType.NEW_STUDENT.getCode());
            this.studentSignUpService.updateSignupResult(record);
            return new RspResult(Status.SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new RspResult(Status.FAIL);
    }

    @RequestMapping("export")
    ModelAndView export(SignUpQueryVO vo) {
        ModelAndView modelAndView = new ModelAndView();
        try {
            vo.setSignUpType(StudentSignUpType.NEW_STUDENT.getCode());
            Page page = new Page();
            page.setParams(vo);
            page.setPageSize(2147483646);
            List list = this.studentSignUpService.selectListByPage(page);

            LinkedHashMap map = new LinkedHashMap();
            String title = "报读学生名单";
            map.put(title, list);

            List headNames = new ArrayList();
            headNames.add(new String[]{"报名状态", "结果反馈", "报名号", "学生姓名", "学生性别", "生日", "证件号", "报读年级", "原就读学校", "家庭详细住址", "户籍详细住址", "民族",
                    "健康状况", "爸爸是否监护人", "爸爸姓名", "爸爸电话", "爸爸单位", "妈妈是否监护人", "妈妈姓名", "妈妈电话", "妈妈单位", "推荐人", "报名时间"});
            List fieldNames = new ArrayList();
            fieldNames.add(new String[]{"statusText", "resultMessage", "signupNo", "studentName", "studentSex", "studentBirthday", "studentIdNo", "signGrade", "baseSchool",
                    "familyAddr", "houseAddr", "nation", "healthy", "fatherIsGuardian", "fatherName", "fatherPhone", "fatherCompany", "motherIsGuardian", "motherName", "motherPhone", "motherCompany",
                    "recommender", "signUpTime"});

            String[] titles = {title};

            ExportSetInfoUtil setInfo = new ExportSetInfoUtil(map, titles, headNames, fieldNames, null);
            this.request.setAttribute("exportDatas", setInfo);

            modelAndView = new ModelAndView(new ExcelExportUtil(title + ".xls", ""));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return modelAndView;
    }

    @RequestMapping("import")
    @ResponseBody
    Object courseImport(@RequestParam("files") MultipartFile buildInfo) {
        try {
            InputStream inputStream = buildInfo.getInputStream();
            AdminUser adminUser = getAdminUser();
            Workbook wookbook = null;
            String filename = buildInfo.getOriginalFilename();
            String fileType = filename.substring(filename.lastIndexOf(".") + 1,
                    filename.length());
            if (fileType.equals("xls"))
                try {
                    wookbook = new HSSFWorkbook(inputStream);
                } catch (Exception e) {
                    wookbook = null;
                    wookbook = new XSSFWorkbook(inputStream);
                }
            else {
                wookbook = new XSSFWorkbook(inputStream);
            }

            Sheet sheet = wookbook.getSheetAt(0);
            int coloumNum = sheet.getRow(0).getPhysicalNumberOfCells();
            int rowNum = sheet.getPhysicalNumberOfRows();
            if (rowNum <= 1) {
                return new RspResult(Status.TEMPLATE_DATA_NULL);
            }
            Map<Integer, String> map = new HashMap<>();
            Row headRow = sheet.getRow(0);
            for (int i = 0; i < coloumNum; i++) {
                Cell cell = headRow.getCell((short) i);
                String val = CellUtil.getCellValue(cell);
                if (StringUtils.isNotBlank(val)) {
                    map.put(Integer.valueOf(i), StringUtil.removeSpecialChar(val));
                }
            }
            List<StudentSignUp> list = new ArrayList<>();
            List<String> errorList = new ArrayList<>();

            for (int i = 1; i < rowNum; i++) {
                Row row = sheet.getRow(i);

                if (row != null) {
                    StudentSignUp plan = new StudentSignUp();
                    List<String> error = new ArrayList<>();
                    for (int j = 0; j < coloumNum; j++) {
                        Cell cell = row.getCell((short) j);
                        if (cell != null) {
                            String val = CellUtil.getCellValue(cell);
                            if (j == 0) {
                                plan.setStatus(StudentSignupStaus.getCode(val));
                                if (StringUtils.isBlank(plan.getStatus()))
                                    error.add((String) map.get(Integer.valueOf(j)) + "值有误");
                            } else if (j == 1) {
                                plan.setResultMessage(val);
                                if (StringUtils.isBlank(val))
                                    error.add((String) map.get(Integer.valueOf(j)) + "不能为空");
                            } else if (j == 2) {
                                plan.setSignupNo(val);
                                if (!StringUtils.isBlank(val)) break;
                                error.add((String) map.get(Integer.valueOf(j)) + "不能为空");

                                break;
                            }
                            plan.setSchoolId(adminUser.getTeacherInfo().getSchoolId());
                        }
                    }
                    if (!StringUtil.isNullOrEmpty(error))
                        errorList.add("第" + (i + 1) + "行" + String.join("/|", error));
                    else {
                        list.add(plan);
                    }
                }
            }

            if (!StringUtil.isNullOrEmpty(errorList)) {
                return new RspResult(Status.FAIL.getCode(), String.join("，", errorList));
            }
            studentSignUpService.updateBatchSignupStatus(list);
            return new RspResult(Status.SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new RspResult(Status.TEMPLATE_ERROR);
    }
}